package com.qfmy.app.service.impl.novel;

import com.qfmy.app.mapper.novel.ReadTimeMapper;
import com.qfmy.app.service.novel.ReadTimeService;
import com.qfmy.common.exception.BaseException;
import com.qfmy.common.login.LoginUser;
import com.qfmy.common.login.LoginUserHolder;
import com.qfmy.common.result.ResultCodeEnum;
import com.qfmy.model.entity.novel.ReadTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 清风明月
 * @Package com.qfmy.app.service.impl.novel
 * @date 2025/4/15
 * @description 阅读记录
 */
@Service
@SuppressWarnings("all")
public class ReadTimeServiceImpl implements ReadTimeService {

    /**
     * 注入mapper
     */
    @Autowired
    private ReadTimeMapper readTimeMapper;

    /**
     * 获取阅读时长
     * @return
     */
    @Override
    public Integer getReadTime() {
        //获取当前用户id
        Integer userId = getUserId();
        //查询阅读时长
        return readTimeMapper.getReadTime(userId);
    }

    /**
     * 更新阅读时长
     * @param readTime
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateReadTime(String readTime) {
        //获取当前用户id
        Integer userId = getUserId();
        //根据用户id查询阅读
       ReadTime rd =  readTimeMapper.selectByRead(userId);
       //判断是否存在
        if(rd == null) {
            //不存在则新增
            ReadTime r = new ReadTime();
            r.setUserId(userId);
            r.setDayTime(readTime);
            readTimeMapper.insert(r);
        }else
        {
            //存在则更新
            rd.setDayTime(readTime);
            readTimeMapper.updateById(rd);
        }
    }

    /**
     * 获取当前用户id
     * @return
     */
    private Integer getUserId() {
        //获取当前用户id
        LoginUser loginUser = LoginUserHolder.getLoginUser();
        //判断是否登录
        if (loginUser == null) {
            throw  new BaseException(ResultCodeEnum.TOKEN_INVALID);
        }
        return loginUser.getUserId();
    }
}
